$(function () {
	vm.getDept();
    $("#jqGrid").jqGrid({
        url: baseURL + 'student/student/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true ,align:"center"},
			{ label: '所属单位', name: 'deptName', index: 'dept_name', width: 80 ,align:"center"}, 			
			/*{ label: '角色', name: 'roleName', index: 'roleName', width: 80 }, 	*/		
			{ label: '单位编号', name: 'deptNumber', index: 'dept_number', width: 80 , hidden:true}, 			
			{ label: '真实姓名', name: 'name', index: 'name', width: 80 ,align:"center"}, 			
			{ label: '登录名', name: 'userName', index: 'user_name', width: 80 ,align:"center"}, 			
			/*{ label: '用户密码', name: 'userPwd', index: 'user_pwd', width: 80 }, */			
			{ label: '用户手机号', name: 'phone', index: 'phone', width: 80 ,align:"center"}, 			
			{ label: '岗位id', name: 'post', index: 'post', width: 80 , hidden:true}, 			
			/*{ label: '兼职岗位id', name: 'partTimePost', index: 'part_time_post', width: 80 },*/ 			
			{ label: '工号', name: 'workid', index: 'workId', width: 80 , hidden:true}, 			
			/*{ label: '性别 0女 1男', name: 'sex', index: 'sex', width: 80 },*/ 			
			{ label: '创建时间/注册日期', name: 'createTime', index: 'create_time',align:"center", width: 80 , formatter:function(value,options,row){
                return new Date(value).Format('yyyy-MM-dd HH:mm:ss');}},			
			/*{ label: '修改时间', name: 'updateTime', index: 'update_time', width: 80 }, */			
			{ label: '创建人id', name: 'userId', index: 'user_id', width: 80 , hidden:true}, 			
			{ label: '创建人', name: 'createName', index: 'createName', width: 80 }, 	
			{ label: '状态', name: 'disFlag', index: 'dis_flag', width: 80 ,align:"center" , formatter: function(value, options, row){
				return value === 1 ? 
						'<span class="label label-danger" value="1">禁用</span>' : 
						'<span class="label label-success" value="0">正常</span>';
			}},
			{ label: '状态', name: 'disFlag', index: 'dis_flag', width: 80 , hidden:true}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "selectStudentList.list",
            page: "selectStudentList.pageNum",
            total: "selectStudentList.pages",
            records: "selectStudentList.total"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    
//    new AjaxUpload('#upload', {
//        action: baseURL + "sys/oss/uploadPic",
//        name: 'file',
//        autoSubmit:true,
//        responseType:"json",
//        onSubmit:function(file, extension){
//            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
//                alert('只支持jpg、png、gif格式的图片！');
//                return false;
//            }
//        },
//        onComplete : function(file, r){
//            if(r.code == 0){
//                alert(r.url);
//                vm.reload();
//            }else{
//                alert(r.msg);
//            }
//        }
//    });

});

var setting = {
		  data: {
		      simpleData: {
		         enable: true,
		         idKey: "deptId",
		         pIdKey: "parentId",
		         rootPId: -1
		        },
		      key: {
		         url:"nourl"
		      }
		  }
	};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		roleLists:{},
		showList: true,
		showLists: true,
		showAdd:false,
		title: null,
		student: {deptName:null, deptId:null},
        majorRoleId: "",
		postList: {},
        majorRoleList: [],
        useTimeTypeList: [],
        useTimeTypeCode: null,
		imp:false,
		studentExcel:'',
		showPicture:false,
		q:{
			studentName: null,
			deptId:null,
			deptName:null,
			deptNo:null,
        },
        detailShowList:false,
		
	},
	props: ["uploadType", "imgUrl", "imgWidth", "imgHeight"],
    created:function(){
        this.avatar = this.imgUrl
    },
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.showAdd = true;
			vm.roleLists = {},
			vm.title = "新增";
			vm.student = {deptName:null, deptId:null};
//			vm.getRoleList();
			vm.getPostList();
			vm.getMajorRoleList();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
			vm.showAdd = true;
            vm.title = "修改";
            
            vm.getInfo(id);
            
            vm.getPostList();
            vm.getMajorRoleList();
		},
		getDept: function(){
			//加载部门树
			$.get(baseURL + "sys/dept/list", function(r){
				ztree = $.fn.zTree.init($("#deptTree"), setting, r);
				var node = ztree.getNodeByParam("deptId", vm.student.studentDeptId);
				if(node != null){
					ztree.selectNode(node);
					//修改时，不能回显.下边的解决了.
//					Vue.set(vm.student, 'deptName', node.name)
					vm.student.deptName = node.name;
					Vue.set(vm.q, 'deptName', node.name)
					Vue.set(vm.q, 'deptNo', node.deptNo)
				}
			})
		},
		deptTree: function(){
	        layer.open({
	            type: 1,
	            offset: '50px',
	            skin: 'layui-layer-molv',
	            title: "选择部门",
	            area: ['300px', '450px'],
	            shade: 0,
	            shadeClose: false,
	            content: jQuery("#deptLayer"),
	            btn: ['确定', '取消'],
	            btn1: function (index) {
	                var node = ztree.getSelectedNodes();
	                //选择上级部门
	                vm.student.studentDeptId = node[0].deptId;
	                vm.student.deptName = node[0].name;
	                
	                vm.q.deptId = node[0].deptId;
					vm.q.deptName = node[0].name;
					vm.q.deptNo = node[0].deptNo;
	                
	                layer.close(index);
	            }
	        });
	    },
	    updateState: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			var rowData = $("#jqGrid").jqGrid('getRowData',id);
			vm.student.id=id;
			vm.student.disFlag=rowData.disFlag;
			
			var url = "student/student/updateState";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.student),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		impo: function (event) {
			
			if(vm.student.studentDeptId==null){
				alert("请选择导入部门");
				return;
			}
			var formData = new FormData();
			formData.append('file', $('#file')[0].files[0]);
			formData.append('deptId', vm.student.studentDeptId);
			formData.append('majorRoleId', vm.majorRoleId); // 专业角色.
			formData.append('useTimeTypeCode', vm.useTimeTypeCode); // 授权使用时间.
			$.ajax({
                url: baseURL + "student/student/imports",
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function (r) {
                	console.log(r);
                	var list = r.oldStudentList;
                	var count=r.count;
                	var al="错误数据:";
                	
                	if(list.length>0){
                		for(var i=0; i<list.length;i++){
                			var userName = list[i].userName;
                			var name = list[i].name;
                			var phone = list[i].phone;
                			
                			al +="用户名："+ userName +"真实姓名:" + name+"手机号: " + phone +'</br>';
                		}
                		alert(al);
                	}else{
                		alert("成功导入:"+r.count+"条数据");
                	}
                	
                	vm.student.studentDeptId=null;
                	vm.student.deptName=null;
                	vm.studentExcel=null;
                	vm.reload();
                	
                },
                error: function (err) {
                }

			});
			
		},
		download:function(){
			location.href=baseURL+"student/student/download";
		},
		saveOrUpdate: function (event) {
			var url = vm.student.id == null ? "student/student/save" : "student/student/update";
            var param = {
                "student":vm.student,
                "majorRoleId": vm.majorRoleId
            };
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(param),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "student/student/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "student/student/info/"+id, function(r){
                vm.student = r.map.student;
                vm.majorRoleId = r.map.majorRoleStudent.majorRoleId;
                vm.getDept();
            });
		},
		detail:function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
			vm.showAdd = false;
			vm.detailShowList = true;
		    vm.title = "详情";
		        
		    vm.getInfo(id);
		    vm.getDept();
		    vm.getPostList();
		},
		reset: function(id){
			var id = getSelectedRow();
			
			if(id == null){
				return ;
			}
			
			confirm('确定要重置密码吗？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "student/student/reset",
                    contentType: "application/json",
				    data: JSON.stringify(id),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		reload: function (event) {
			vm.showList = true;
			vm.showAdd = false;
			vm.imp = false;
			vm.detailShowList = false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'studentName': vm.q.studentName,"deptNo":vm.q.deptNo},
                page:page
            }).trigger("reloadGrid");
		},
		//获取角色列表.
		getRoleList: function (event) {
			$.get(baseURL + "sys/role/getList", function(r){
				vm.roleLists = r.list;
            });
		},
        //获取角色列表.
        getMajorRoleList: function (event) {
            $.get(baseURL + "student/majorRole/getList", function(r){
                vm.majorRoleList = r.list;
            });
        },
		//获取岗位列表.
		getPostList: function (event) {
			$.get(baseURL + "student/post/getList", function(r){
				vm.postList = r.postList;
            });
		},
		//显示导入页面.
		dao:function(){
			vm.showList = false;
			vm.showAdd = false;
			vm.imp = true;
			vm.getMajorRoleList();
			vm.getUseTimeTypeEnumList();
		},
        // 获取授权使用时间枚举list.
        getUseTimeTypeEnumList: function (event) {
            $.get(baseURL + "student/studentManager/getUseTimeTypeEnumList", function(r){
                vm.useTimeTypeList = r.list;
            });
        },
		pic:function(){
			vm.showList = false;
			vm.showAdd = false;
			vm.imp = false;
			vm.showPicture = true;
		},
		uploadPic:function(event){
			alert("12")
			  let reader =new FileReader();  
			  let img1=event.target.files[0];  
			  let type=img1.type;//文件的类型，判断是否是图片  
			  let size=img1.size;//文件的大小，判断图片的大小  
			  if(size>3145728){  
			      alert('请选择3M以内的图片！');  
			      return false;  
			  }  
			
			var formData = new FormData();
			formData.append('file', $('#file1')[0].files[0]);
			$.ajax({
                url: baseURL + "sys/oss/uploadPic",
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function (r) {
                	console.log(r);
                	
                	if(r.code==0){
                		vm.student.pictureUrl=r.url
                	}else{
                		
                	}
                	
                },
                error: function (err) {
                }

			});

			
			
		},
		//清空查询输入内容
		clear:function(){
			vm.q.studentName = null;
			vm.q.deptNo=null
			vm.q.deptName=null
			vm.q.deptId=null
			
			vm.reload();
		}
	}
});

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}